#include <stdio.h>
#include <stdlib.h>

#include "mpi.h"

int main(int argc, char *argv[])
{
      int    i, n=500000000;
      double h, pi, x;

      int    me, nprocs;
      double piece;
      MPI_Init (&argc, &argv);
      MPI_Comm_size (MPI_COMM_WORLD, &nprocs);
      MPI_Comm_rank (MPI_COMM_WORLD, &me);
      if (me == 0)
      {
         printf("%s", "Input number of intervals:\n");
      }
      MPI_Bcast (&n, 1, MPI_INT,
                 0, MPI_COMM_WORLD);
      h     = 1. / (double) n;
      piece = 0.;
      for (i=me+1; i <= n; i+=nprocs)
      {
           x     = (i-1)*h;
           piece = piece + (
                                   4/
                              (1+(x)*(x))
                                   +
                                   4/
                              (1+(x+h)*(x+h))
                                               ) / 2 * h;
      }

      printf("%d: pi = %25.15f\n", me, piece);
      MPI_Reduce (&piece, &pi, 1, MPI_DOUBLE,
                  MPI_SUM, 0, MPI_COMM_WORLD);
      if (me == 0)
      {
         printf("pi = %25.15f\n", pi);
      }
      MPI_Finalize();
      return 0;
}
